package cn.stronglink.assetmanage.business.search.view;

import android.app.Dialog;
import android.media.Image;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import android.widget.TextView;


import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.util.ArrayList;
import java.util.List;

import Scaner.scan.IScanerListener;
import Scaner.scan.TimerInfraraedScaner;
import cn.stronglink.assetmanage.MainActivity;
import cn.stronglink.assetmanage.R;
import cn.stronglink.assetmanage.business.inventory.view.detail.InventoryDetailFragment;
import cn.stronglink.assetmanage.business.inventory.view.goods.GoodsDetailFragment;
import cn.stronglink.assetmanage.business.search.adapter.SearchAdapter;
import cn.stronglink.assetmanage.business.search.model.SearchModel;
import cn.stronglink.assetmanage.business.search.presenter.SearchListPresenter;
import cn.stronglink.assetmanage.business.search.view.AssisChange.AssisChangeFragment;
import cn.stronglink.assetmanage.dao.DaoManager;
import cn.stronglink.assetmanage.dao.SyncTypesDao;
import cn.stronglink.assetmanage.entity.Result;
import cn.stronglink.assetmanage.entity.Room;
import cn.stronglink.assetmanage.entity.SearchAsset;
import cn.stronglink.assetmanage.entity.Status;
import cn.stronglink.assetmanage.entity.SyncTypes;
import cn.stronglink.assetmanage.entity.Type;
import cn.stronglink.assetmanage.index.entity.PromissionEntity;
import cn.stronglink.assetmanage.index.view.onRecyclerListener;
import cn.stronglink.assetmanage.utils.Constants;
import cn.stronglink.assetmanage.utils.ToastUtil;
import cn.stronglink.assetmanage.widget.CustomProgressDialog;
import cn.stronglink.netrequest.business.search.SearchService;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * 检索查找fragment
 * Created by zhengjinglan on 2018/6/19.
 */

public class SearchFragment extends Fragment implements View.OnClickListener ,ISearchView {
    private EditText et_name,et_rfid,et_sn;
    private Spinner sp_type,sp_room,sp_status;
    private ImageView iv_scan,iv_search;
    private int statusId;
    private String typeId;
    private String roomId;
    private List<SearchAsset> searchAssetList;
    private RecyclerView recyclerView;
    private SearchAdapter searchAdapter;
    private SearchListPresenter searchListPresenter;
    private TimerInfraraedScaner scaner;
    private Dialog mDialog;
    private TextView txt_title_right, txt_title_left, txt_main_title;
    private SwipeRefreshLayout refresh_list_search;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_search, container, false);
        initView(view);
        initData();
        return view;
    }

    private void initData() {
        searchListPresenter = new SearchListPresenter(getActivity(),this);
        List<Type> typeList = searchListPresenter.queryTypeList();
        List<Status> statusList = searchListPresenter.queryStatusList();
        List<Room> roomList = searchListPresenter.queryRoomList();

        ArrayAdapter<Type> typeArrayAdapter = new ArrayAdapter<Type>(getActivity(), android.R.layout.simple_dropdown_item_1line,typeList);
        sp_type.setAdapter(typeArrayAdapter);
        sp_type.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                typeId =((Type)sp_type.getSelectedItem()).getId_();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        ArrayAdapter<Room> roomArrayAdapter = new ArrayAdapter<Room>(getActivity(),android.R.layout.simple_dropdown_item_1line,roomList);
        sp_room.setAdapter(roomArrayAdapter);
        sp_room.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                roomId = ((Room)sp_room.getSelectedItem()).getId_();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        ArrayAdapter<Status> statusArrayAdapter = new ArrayAdapter<Status>(getActivity(),android.R.layout.simple_dropdown_item_1line,statusList);
        sp_status.setAdapter(statusArrayAdapter);
        sp_status.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                statusId= ((Status)sp_status.getSelectedItem()).getId();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        queryList();

    }


    private void initView(View view) {
        txt_title_right = this.getActivity().findViewById(R.id.txt_right_title);
        txt_title_right.setVisibility(View.GONE);
        txt_title_left = this.getActivity().findViewById(R.id.txt_left_title);
        txt_title_left.setVisibility(View.GONE);
        txt_main_title = this.getActivity().findViewById(R.id.txt_main_title);
        txt_main_title.setText("检索查找");
        et_name = view.findViewById(R.id.et_search_in_dev_name);
        et_rfid = view.findViewById(R.id.et_search_in_rfid);
        et_sn = view.findViewById(R.id.et_search_in_assis_no);
        sp_room = view.findViewById(R.id.sp_room);
        sp_status = view.findViewById(R.id.sp_status);
        sp_type = view.findViewById(R.id.sp_type);
        iv_scan = view.findViewById(R.id.iv_scan);
        iv_search = view.findViewById(R.id.iv_search);
        recyclerView = view.findViewById(R.id.search_recyclerView);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        //设置布局管理器
        recyclerView.setLayoutManager(layoutManager);
        //设置为垂直布局，这也是默认的
        layoutManager.setOrientation(OrientationHelper.VERTICAL);
        recyclerView.addItemDecoration(new DividerItemDecoration(getActivity(),DividerItemDecoration.VERTICAL));
        searchAdapter = new SearchAdapter(getActivity());
        //设置Adapter
        recyclerView.setAdapter(searchAdapter);
        searchAdapter.setOnItemClickListener(onRecyclerListener);
        iv_scan.setOnClickListener(this);
        iv_search.setOnClickListener(this);
        refresh_list_search = view.findViewById(R.id.refresh_list_search);
        refresh_list_search.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                queryList();
            }
        });
        try {
            scaner = new TimerInfraraedScaner(getActivity());
            scaner.setScanerListener(new IScanerListener() {
                @Override
                public void onScaning(List<String> data) {
                    String value = data.get(data.size()-1).replace("\r","");
                    searchListPresenter.queryByScan(value);
                }
            });
        }catch (Exception e){
            e.printStackTrace();
            ToastUtil.toastShort("rfid硬件加载失败");
        }



    }

    private onRecyclerListener onRecyclerListener = new onRecyclerListener() {
        @Override
        public void onItemClicked(View v, int postion) {
            SearchAsset searchAsset = searchAssetList.get(postion);
            MainActivity activity = (MainActivity) getActivity();
            PromissionEntity pe = new PromissionEntity();
            pe.setFragment(new AssisChangeFragment());
            pe.setPosition(MainActivity.FRAGMENT_CUSTOM_ID);
            pe.setTitle("资产详情");
            // 设置打开盘点详情后传递的参数
            Bundle bundle=new Bundle();
            bundle.putSerializable(Constants.CHECK_IN_DETAIL_NO, searchAsset.getId_());
            pe.setBundle(bundle);
            activity.onEventRegister(pe);
        }
    };

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.iv_scan:   // 扫一扫
                et_name.clearFocus();
                et_rfid.clearFocus();
                et_sn.clearFocus();
                if (scaner == null){
                    scaner = new TimerInfraraedScaner(getActivity());
                }
                scaner.playSingle();
                break;
            case R.id.iv_search: // 查询
                searchListPresenter.queryByInput();
                break;
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (scaner!=null){
            scaner.stop();
            scaner.destory();
        }
    }

    @Override
    public void onSuccess(final List<SearchAsset> searchAssets) {
        // 更新ui
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (searchAssets!=null){
                    searchAssetList = searchAssets;
                    searchAdapter.notifyDatasChanged(searchAssets);
                }
            }
        });

    }

    @Override
    public void onFail(Exception e) {
        // 显示异常

        ToastUtil.toastShort(e.getMessage());
    }

    @Override
    public String getAssetNameText() {
        return et_name.getText().toString();
    }

    @Override
    public String getAssetNoText() {
        return et_sn.getText().toString();
    }

    @Override
    public String getRfidText() {
        return et_rfid.getText().toString();
    }

    @Override
    public String getAssetType() {
        return typeId;
    }

    @Override
    public String getAssetRoom() {
        return roomId;
    }

    @Override
    public int getAssetStatus() {
        return statusId;
    }

    @Override
    public void showProgress(String msg) {
        mDialog = CustomProgressDialog.createLoadingDialog(getActivity(), msg);
        mDialog.setCancelable(false);
        mDialog.show();
    }

    @Override
    public void hideProgress() {
        if(mDialog!=null){
            mDialog.dismiss();
        }
    }



    public void queryList() {
        // 1.自动 2.离线
        SyncTypes syncType = DaoManager.getDaoSession(getContext()).getSyncTypesDao()
                .queryBuilder().where(SyncTypesDao.Properties.IsSelected.eq(true)).unique();
        int tp = 0;
        if (syncType != null) {
            tp = syncType.getSyscTs();
        }

        if (tp == 1) {
            queryAssetListFromWeb();
        } else {
            searchListPresenter.queryAssetListFromLocal();
            refresh_list_search.setRefreshing(false);
        }
    }



    // 查询资产列表
    private void queryAssetListFromWeb() {
        try {
            SearchService searchService = new SearchService();

            searchService.downloadAssetData(new Callback() {
                @Override
                public void onFailure(Call call, final IOException e) {
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            ToastUtil.toastShort(e.getMessage());
                            refresh_list_search.setRefreshing(false);
                        }
                    });

                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    String json = response.body().string();
                    Result<List<SearchAsset>> result = null;
                    Gson gson = new Gson();

                    result = gson.fromJson(json, new TypeToken<Result<List<SearchAsset>>>() {
                    }.getType());
                    if (result != null && result.getHttpCode() == HttpURLConnection.HTTP_OK) {
                        final List<SearchAsset> searchAssetList = result.getData();
                        if (searchAssetList != null && searchAssetList.size() > 0) {
                            searchListPresenter.saveDataToLocal(searchAssetList);
                            onSuccess(searchAssetList);
                            getActivity().runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    ToastUtil.toastShort("下载资产列表成功");
                                    refresh_list_search.setRefreshing(false);
                                }
                            });

                        }
                    }else {
                        final Result<List<SearchAsset>> finalResult = result;
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                ToastUtil.toastShort(finalResult.getHttpCode()+"");
                                refresh_list_search.setRefreshing(false);
                            }
                        });
                    }

                }
            });
        } catch (final Exception e) {
            e.printStackTrace();
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    refresh_list_search.setRefreshing(false);
                }
            });

        }
    }
}
